﻿using UnityEngine;
using System.Collections.Generic;

public class SoundSystem 
{
	public static bool isMute = false;
	
	private static List<AudioClip> audioSounds;

	/// <summary>
	/// The instance.
	/// </summary>
	private static SoundSystem instance;
	public static SoundSystem Instance
	{
		get 
		{
			if (instance == null)
			{
				instance = new SoundSystem();

				Instance.GetSoundsFromResources();
			}

			return instance;
		}
	}

	private void GetSoundsFromResources()
	{
		Debug.Log("Sounds Added");
		audioSounds = new List<AudioClip>();

		audioSounds.Add((AudioClip)Resources.Load<AudioClip>("Sounds/ButtonTap"));
	}

	/// <summary>
	/// Playes the sound by the name provided.
	/// </summary>
	/// <param name="soundName">Sound name.</param>
	public void PlaySoundByName(string soundName)
	{
		if (isMute)	return;

		// Find the clip.
		AudioClip clip = FindClipByName(soundName);

		if (clip == null)
		{
			Debug.LogError("No Clip Was Found - Audio Manager");
			return;
		}

		// Create an empty game object.
		GameObject go = new GameObject("Audio_" +  clip.name);

		//Create the source
		AudioSource source = go.AddComponent<AudioSource>();
		source.clip = clip;
		source.volume = 1f;
		source.pitch = 1f;
		source.Play();

		GameObject.Destroy(go, clip.length);
	}

	/// <summary>
	/// Returns the audio clip that matches the name.
	/// </summary>
	/// <returns>The clip.</returns>
	/// <param name="soundName">Sound name.</param>
	private AudioClip FindClipByName(string soundName)
	{
		for (int i = 0; i < audioSounds.Count; ++i)
		{
			if (audioSounds[i].name == soundName)
			{
				Debug.Log("SAPE:::" + audioSounds[i].name);
				return audioSounds[i];
			}
		}

		return null;
	}
}